#!/bin/sh
# Using external pipe with st, give a dmenu prompt of recent commands,
# allowing the user to copy the output of one.
# awk, dmenu, tac (or tail -r) and xclip are required for this script.
# By Ed Morton and veltza
# https://stackoverflow.com/a/68688237

# We prefer to use GNU tools because they're guaranteed to work with this script
AWK=$(command -v gawk || echo awk)
TAC=$(command -v gtac || command -v tac || echo "tail -r")

tmpfile=$(mktemp /tmp/st-cmd-output.XXXXXX) || exit

trap 'rm -f "$tmpfile"; exit' 0 1 15

tr -d '\0' > "$tmpfile"

ps1=$($AWK 'NF{line=$1} END{gsub(/\\/, "\\\\", line); print line}' "$tmpfile")

chosen=$($TAC "$tmpfile" \
    | $AWK -v ps1="$ps1" 'index($0,ps1) && c++' \
    | dmenu -p "Copy which command's output?" -i -l 10 \
    | $AWK '{gsub(/\\/, "\\\\"); print}')

[ -z "$chosen" ] && exit

$AWK -v chosen="$chosen" -v ps1="$ps1" \
    '$0==chosen{p=1;print;next} p&&index($0,ps1){p=0};p' "$tmpfile" \
    | xclip -selection clipboard
